/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-28 08:32:51
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-09-27 11:11:56
 * @FilePath: /react18-vite-admin/src/store/modules/app.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { create } from 'zustand';
import i18n from 'i18next';

import type { AppStore, DeviceType } from '@/typings/store/app';
import {
    getSidebarStatus,
    setSidebarStatus as setStorageSidebarStatus,
    getAppSettings,
    setAppSettings
} from '@/utils';
import defaultSettings from '@/settings';

export const useAppStore = create<AppStore>((set) => {
    const appSettings = getAppSettings() ?? defaultSettings;
    i18n.init(() => {
        i18n.changeLanguage(appSettings.language);
    })
    return {
        // 语言
        lang: appSettings.language,
        // 设置语言
        setLang: (lang: AppLangType) => {
            set(() => ({ lang }));
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                language: lang
            });
            i18n.changeLanguage(lang);
        },
        sidebarStatus: getSidebarStatus() ?? 'closed',
        sidebar: {
            opened: getSidebarStatus() === 'opened',
            withoutAnimation: false
        },
        setSidebarStatus: (status: AppSidebarStatus) =>
            set(() => ({ sidebarStatus: status })),
        setSidebar: (opt: { opened?: boolean; withoutAnimation?: boolean }) => {
            set((state) => ({
                sidebar: {
                    ...state.sidebar,
                    ...opt
                }
            }));
        },
        device: 'desktop',
        setDevice: (device: DeviceType) => set(() => ({ device })),
        activeIds: [],
        setActiveIds: (activeIds: string[]) => set(() => ({ activeIds })),
        size: appSettings.size,
        setSize(size) {
            set({
                size
            });
            setAppSettings({
                ...(getAppSettings() ?? defaultSettings),
                size
            });
        }
    };
});

export const useApp = () => {
    const { setSidebarStatus, setSidebar } = useAppStore((state) => state);

    const toggleSidebar = () => {
        const opened = useAppStore.getState().sidebar.opened;
        setSidebar({
            opened: !opened
        });
        setSidebarStatus(opened ? 'closed' : 'opened');
        setStorageSidebarStatus(opened ? 'closed' : 'opened');
    };

    return {
        toggleSidebar
    };
};
